import java.sql.SQLException;
import java.text.ParseException;
import java.util.Scanner;

public class Main {
    private static Scanner scanner = new Scanner(System.in);
    private static StudentService studentService = new StudentService();
    private static ReservationService reservationService = new ReservationService();
    private static Student loginStudent = null;

    public static void main(String[] args) {
        System.out.println("===== 大学自习室管理系统 =====");
        System.out.println("功能：注册、登录、查看座位、预约座位、查看我的预约、修改密码、取消预约");
        mainMenuLoop();
    }


    private static void mainMenuLoop() {
        while (true) {
            if (loginStudent == null) {
                showUnauthorizedMenu();
            } else {
                showAuthorizedMenu();
            }
        }
    }


    private static void showUnauthorizedMenu() {
        System.out.println("\n=== 主菜单 ===");
        System.out.println("1. 登录");
        System.out.println("2. 注册");
        System.out.println("3. 退出系统");
        System.out.print("请选择：");

        int choice;
        try {
            choice = Integer.parseInt(scanner.nextLine().trim());
        } catch (NumberFormatException e) {
            System.out.println("输入错误！请输入数字1-3");
            return;
        }

        switch (choice) {
            case 1: handleLogin(); break;
            case 2: handleRegister(); break;
            case 3: System.out.println("系统已退出！"); scanner.close(); System.exit(0);
            default: System.out.println("无效选项！");
        }
    }


    private static void showAuthorizedMenu() {
        System.out.println("\n=== 学生功能菜单 ===");
        System.out.println("1. 查看座位状态");
        System.out.println("2. 预约座位");
        System.out.println("3. 查看我的预约");
        System.out.println("4. 修改密码");
        System.out.println("5. 取消预约"); // 第五天新增
        System.out.println("6. 退出登录"); // 序号调整
        System.out.print("请选择：");

        int choice;
        try {
            choice = Integer.parseInt(scanner.nextLine().trim());
        } catch (NumberFormatException e) {
            System.out.println("输入错误！请输入数字1-6");
            return;
        }

        switch (choice) {
            case 1: handleShowSeats(); break;
            case 2: handleReserveSeat(); break;
            case 3: handleShowMyReservations(); break;
            case 4: handleUpdatePassword(); break;
            case 5: handleCancelReservation(); break; // 第五天新增
            case 6: loginStudent = null; System.out.println("已退出登录！"); break;
            default: System.out.println("无效选项！");
        }
    }


    private static void handleShowSeats() {
        try {
            System.out.println("\n=== 查看座位状态 ===");
            System.out.print("请输入查询时间（格式：yyyy-MM-dd HH:mm）：");
            String timeStr = scanner.nextLine().trim();
            String seatsStatus = reservationService.getSeatsStatus(timeStr);
            System.out.println(seatsStatus);
        } catch (ParseException e) {
            System.out.println("❌ 时间格式错误！");
        } catch (SQLException e) {
            System.out.println("❌ 数据库错误：" + e.getMessage());
        }
    }


    private static void handleReserveSeat() {
        try {
            System.out.println("\n=== 预约座位 ===");
            System.out.print("请输入预约时间：");
            String timeStr = scanner.nextLine().trim();
            System.out.print("请输入座位号（1-10）：");
            int seatNo = Integer.parseInt(scanner.nextLine().trim());

            boolean success = reservationService.reserveSeat(loginStudent.getId(), seatNo, timeStr);
            if (success) {
                System.out.println("✅ 预约成功！");
            } else {
                System.out.println("❌ 预约失败：座位无效或已被预约");
            }
        } catch (NumberFormatException e) {
            System.out.println("❌ 座位号必须是数字！");
        } catch (ParseException e) {
            System.out.println("❌ 时间格式错误！");
        } catch (SQLException e) {
            System.out.println("❌ 数据库错误：" + e.getMessage());
        }
    }


    private static void handleShowMyReservations() {
        try {
            System.out.println("\n=== 查看我的预约 ===");
            String myReservations = reservationService.getMyReservations(loginStudent.getId());
            System.out.println(myReservations);
        } catch (SQLException e) {
            System.out.println("❌ 查询失败：数据库错误 - " + e.getMessage());
        }
    }


    private static void handleUpdatePassword() {
        try {
            System.out.println("\n=== 修改密码 ===");
            System.out.print("请输入原密码：");
            String oldPassword = scanner.nextLine().trim();
            System.out.print("请输入新密码：");
            String newPassword = scanner.nextLine().trim();
            System.out.print("请再次输入新密码：");
            String confirmPassword = scanner.nextLine().trim();

            if (!newPassword.equals(confirmPassword)) {
                System.out.println("❌ 两次输入的新密码不一致！");
                return;
            }

            studentService.updatePassword(loginStudent.getAccount(), oldPassword, newPassword);
            System.out.println("✅ 密码修改成功！");
        } catch (IllegalArgumentException e) {
            System.out.println("❌ 修改失败：" + e.getMessage());
        } catch (SQLException e) {
            System.out.println("❌ 修改失败：数据库错误 - " + e.getMessage());
        }
    }


    private static void handleCancelReservation() {
        try {
            System.out.println("\n=== 取消预约 ===");
            // 先显示自己的预约记录，方便用户选择要取消的项
            System.out.println("你的当前预约记录：");
            System.out.println(reservationService.getMyReservations(loginStudent.getId()));

            System.out.print("请输入要取消的预约时间（格式：yyyy-MM-dd HH:mm）：");
            String timeStr = scanner.nextLine().trim();

            System.out.print("请输入要取消的座位号：");
            int seatNo = Integer.parseInt(scanner.nextLine().trim());

            // 调用服务层执行取消
            boolean success = reservationService.cancelReservation(loginStudent.getId(), seatNo, timeStr);
            if (success) {
                System.out.println("✅ 取消预约成功！");
            } else {
                System.out.println("❌ 取消失败：该预约不存在（或不属于你）");
            }
        } catch (NumberFormatException e) {
            System.out.println("❌ 座位号必须是数字！");
        } catch (ParseException e) {
            System.out.println("❌ 时间格式错误！");
        } catch (SQLException e) {
            System.out.println("❌ 取消失败：数据库错误 - " + e.getMessage());
        }
    }


    private static void handleLogin() {
        try {
            System.out.println("\n=== 学生登录 ===");
            System.out.print("账号：");
            String account = scanner.nextLine().trim();
            System.out.print("密码：");
            String password = scanner.nextLine().trim();

            Student student = studentService.login(account, password);
            if (student != null) {
                loginStudent = student;
                System.out.println("✅ 登录成功！欢迎 " + student.getName());
            } else {
                System.out.println("❌ 账号或密码错误");
            }
        } catch (IllegalArgumentException e) {
            System.out.println("❌ " + e.getMessage());
        } catch (SQLException e) {
            System.out.println("❌ 数据库错误：" + e.getMessage());
        }
    }


    private static void handleRegister() {
        try {
            System.out.println("\n=== 学生注册 ===");
            System.out.print("账号：");
            String account = scanner.nextLine().trim();
            System.out.print("密码：");
            String password = scanner.nextLine().trim();
            System.out.print("姓名：");
            String name = scanner.nextLine().trim();

            studentService.register(account, password, name);
            System.out.println("✅ 注册成功！");
        } catch (IllegalArgumentException e) {
            System.out.println("❌ " + e.getMessage());
        } catch (SQLException e) {
            if (e.getMessage().contains("Duplicate entry")) {
                System.out.println("❌ 账号已存在！");
            } else {
                System.out.println("❌ 数据库错误：" + e.getMessage());
            }
        }
    }
}